import React, { useState, useImperativeHandle, ReactNode } from 'react';
import { PlusOutlined } from '@ant-design/icons';
import {
  Form,
  Input,
  Button,
  Modal
} from 'antd';

export interface addUserProps {
  childRef?: any,
  addUser?: (e: any) => void,
  updateUser?: (e: any) => void
}

const App = (props: addUserProps) => {
  const [form] = Form.useForm();
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [modelText, setModelText] = useState('添加用户')

  const { childRef } = props


  useImperativeHandle(childRef, () => ({
    showModal: (e: any) => { showModal(e) },
  }))

  const showModal = (e: any) => {
    if (e.id) {
      setModelText('修改用户信息')
      form.setFieldsValue({ ...e, password: '' });
    }
    setIsModalOpen(true);
  };

  const handleOk = () => {
    if (form.getFieldValue().id) {
      props.updateUser && props.updateUser(form.getFieldValue())
    } else if (form.getFieldValue().username && form.getFieldValue().password) {
      props.addUser && props.addUser({ ...form.getFieldValue(), id: '' })
    }
    setIsModalOpen(false);
    form.resetFields();
  };
  const handleCancel = () => {
    setIsModalOpen(false);
    form.resetFields();
    setModelText('添加用户')
  };

  return (
    <>
      <Button type="primary" onClick={showModal} style={{ marginBottom: '10px' }}>
        添加平台账号
      </Button>
      <Modal title={modelText} open={isModalOpen} onOk={handleOk} onCancel={handleCancel}>
        <Form
          name='addUser'
          form={form}
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 14 }}
          layout="horizontal"
          style={{ maxWidth: 600 }}
        >
          <Form.Item label="账号" name={'username'}
            rules={[
              {
                required: true,
                message: '请输入账号',
              },
            ]}
          >
            <Input placeholder='请输入账号' />
          </Form.Item>
          <Form.Item label="密码" name={'password'}
            rules={[
              {
                required: true,
                message: '请输入密码',
              },
            ]}
          >
            <Input placeholder='请输入密码' />
          </Form.Item>
          <Form.Item label="用户头像" name={'imageUrl'}
            rules={[
              {
                required: true,
                message: '请输入Url链接',
              },
            ]}
          >
            <Input placeholder='目前只支持url链接' />
          </Form.Item>

          {/* <Form.Item label="头像" name={'picture'} valuePropName="fileList" rules={[
              {
                required: true,
                message: '请上传头像',
              },
            ]}>
            <Upload action="/upload.do" listType="picture-card">
              <div>
                <PlusOutlined />
                <div style={{ marginTop: 8 }}>Upload</div>
              </div>
            </Upload>
          </Form.Item> */}
        </Form>
      </Modal>
    </>
  );
};

export default App;